package mybatis.web;

import mybatis.pojo.Subject;
import mybatis.services.GradeService;
import mybatis.services.SubjectService;
import mybatis.util.StrUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author 汤舒青
 * @Version 1.0
 */

@WebServlet("/addSubject")
public class SubjectAdd extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("all", GradeService.ME.findAll());
        req.getRequestDispatcher("/WEB-INF/jsp/subjectAdd.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String subName = request.getParameter("subjectname");
        int classHour = StrUtil.toInt(request.getParameter("classhour"));
        Long gradeId =StrUtil.toLong(request.getParameter("gradeid"),1l);
        Subject subject = new Subject();
        subject.setSubjectname(subName);
        subject.setClasshour(classHour);
        subject.setGradeid(gradeId);
        int update = SubjectService.ME.add(subject);
        if (update > 0) {
            out.println("<script>alert('增加成功');window.location.replace('subject');</script>");
        } else {
            out.println("<script>alert('增加失败');window.location.replace('subject');</script>");
        }
    }
}
